package com.fiona.register.zk;

import java.util.List;

import org.apache.curator.framework.CuratorFramework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fiona.common.exception.RemotingException;
import com.fiona.common.extension.ExtensionLoader;
import com.fiona.core.loadbalance.LoadBalance;
import com.fiona.core.message.enums.RpcResponseCodeEnum;
import com.fiona.core.remoting.model.Service;
import com.fiona.register.api.ServiceDiscovery;
import com.fiona.register.zk.util.CuratorUtils;


/**
 * service discovery based on zookeeper
 *
 */
public class ZkServiceDiscovery implements ServiceDiscovery {
	private static Logger logger = LoggerFactory.getLogger(ZkServiceDiscovery.class);
    private final LoadBalance loadBalance;

    public ZkServiceDiscovery() {
        this.loadBalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension("random");
    }

    @Override
    public List<Service> findServiceList(String serviceId) throws RemotingException {
        CuratorFramework zkClient = CuratorUtils.getZkClient();
        List<String> serviceUrlList = CuratorUtils.getChildrenNodes(zkClient, serviceId);
        if (serviceUrlList == null || serviceUrlList.size() == 0) {
            throw new RemotingException(RpcResponseCodeEnum.SERVICE_CAN_NOT_BE_FOUND, serviceId);
        }
        // load balancing
        String targetServiceUrl = loadBalance.selectServiceAddress(serviceUrlList, serviceId);
        logger.info("Successfully found the service address:[{}]", targetServiceUrl);
        String[] socketAddressArray = targetServiceUrl.split(":");
        String host = socketAddressArray[0];
        int port = Integer.parseInt(socketAddressArray[1]);
        return null;
    }
}
